﻿/// <summary>
/// Method called after the page is loaded.
/// </summary>
$(document).ready(function () {
    
    //Create viewmodel instance.
    LoadViewModel();
    ko.applyBindings(viewModel);

    //Load the list of visits.
    viewModel.LoadVisits();

    //Make the list of pictures sortable
    $(function () {
        $("#pictures").sortable();
        $("#pictures").disableSelection();
    });

    //When the pictures are sorted we called viewModel.PicturesListSorted
    $("#pictures").bind("sortupdate", viewModel.PicturesListSorted);

    //Display edit visit panel as tabs.
    $(function () {
        $("#editvisit").tabs();
    });

});

/// <summary>
/// Map instance.
/// </summary
var map;

// <summary>
/// Method called when the map is loaded.
/// </summary
function MapLoaded(sender,args)  
{
    map = sender.getHost();    
}

// <summary>
/// Method called by the map when a new location is double clicked.
/// </summary
function SetVisitLocation(latitude, longitude) {
    viewModel.SelectedVisit().Visit().Latitude(latitude);
    viewModel.SelectedVisit().Visit().Longitude(longitude);
}

/// <summary>
/// The page viewmodel instance.
/// </summary>
var viewModel;

/// <summary>
/// The page viewmodel constructor.
/// </summary>
function LoadViewModel() {

    viewModel =
    {
        /// <summary>
        /// List of visits.
        /// </summary>
        Visits: ko.observableArray([])

        /// <summary>
        /// Gets/sets a boolean indicating whether the list of visits are loading.
        /// </summary>
       , IsLoading: ko.observable(false)

        /// <summary>
        /// Gets/sets a boolean indicating whether Dashboard Tab is selected.
        /// </summary>
        , DashboardTabIsSelected: ko.observable(true)

        /// <summary>
        /// Gets/sets the value of the visibility filter.
        /// </summary>
        /// <remarks>3 possible values : allVisits, visibleVisits, notVisibleVisits</remarks>
        , SelectedFilterVisibility: ko.observable('allVisits')

        /// <summary>
        /// Gets/sets the value filter by visits title.
        /// </summary>
        , FilterText: ko.observable('')

        /// <summary>
        /// Gets/sets the current selected visit.
        /// </summary>
       , SelectedVisit: ko.observable(new VisitQualityViewModel())

        // #endregion
        // #region Methods

        /// <summary>
        /// Load all visits using mal.balades.Web.Administration.VisitService class.
        /// </summary>     
            , LoadVisits: function () {
                this.IsLoading(true);
                var service = new mal.balades.Web.Administration.VisitService();
                service.GetAllVisits(viewModel.onGetAllVisitsSuccess, null, null);
            }

        /// <summary>
        /// Callback method for LoadVisits method.
        /// </summary>   
        /// <param name="visits">The list of visits return by the service.</param>
            , onGetAllVisitsSuccess: function (visits) {
                viewModel.IsLoading(false);

                viewModel.Visits([]);
                for (var i = 0; i < visits.length; i++) {
                    var visit = new VisitQualityViewModel();
                    visit.Load(visits[i]);
                    viewModel.Visits.push(visit);
                }
            }

        /// <summary>
        /// Method called after add new visit.
        /// Add a DoubleClick event handler on the html row.
        /// </summary>   
            , AddDoubleClickEventHandler: function (element) {
                $(element).dblclick(function () { viewModel.SelectVisit(element.id); });
            }

            , OpenVisit: function (visit) {
                this.SelectVisit(visit.VisitID());
            }

            , SelectVisit: function (visitID) {

                this.SelectedVisit().IsSelected(false);

                if (visitID == null) {
                    this.DashboardTabIsSelected(true);
                }
                else {
                    this.DashboardTabIsSelected(false);

                    var visit;
                    for (var i = 0; i < this.VisitsToShow().length; i++) {
                        visit = this.VisitsToShow()[i];

                        if (visit.VisitID() == visitID) {
                            var add = true;
                            this.SelectedVisit(visit);
                            this.SelectedVisit().IsSelected(true);
                            visit.Select();
                        }
                    }
                }
            }

            , AddPicture: function () {
                this.SelectedVisit().Visit().AddPicture();
            }
            
            , Save: function () {
                for (var i = 0; i < this.Visits().length; i++) {
                    this.Visits()[i].Save();
                }
            }
        /// <summary>
        /// Method called when the pictures list is sorted.
        /// </summary>   
            , PicturesListSorted: function (event, ui) {
                var pictureIds = $('#pictures').sortable('toArray');

                viewModel.SelectedVisit().Visit().PicturesListSorted(pictureIds);
            }


        // #endregion        

    }

    viewModel.VisitsToShow = ko.dependentObservable(function () {
        var visibility = null;
        var filterText = this.FilterText();

        if (this.SelectedFilterVisibility() == "visibleVisits")
            visibility = true;
        else if (this.SelectedFilterVisibility() == "notVisibleVisits")
            visibility = false;

        return ko.utils.arrayFilter(this.Visits(), function (visit) {
            var result = true;

            if (visibility != null)
                result = result & visit.Visible() == visibility;

            if (filterText != "")
                result = result & compareText(visit.Title(), filterText);

            return result;
        });
    } .bind(viewModel));

}

function compareText(text1, text2) {
    return formatTextToSearch(text1).indexOf(formatTextToSearch(text2)) >= 0;
}

function formatTextToSearch(text) {
    var result = text.toLowerCase();

    result = result.replace("â", "a");
    result = result.replace("à", "a");
    result = result.replace("é", "e");
    result = result.replace("è", "e");
    result = result.replace("ê", "e");
    result = result.replace("ë", "e");
    result = result.replace("ç", "c");
    result = result.replace("î", "i");
    result = result.replace("ô", "o");

    return result;
}


// Here's a custom Knockout binding that makes elements shown/hidden via jQuery's fadeIn()/fadeOut() methods
// Could be stored in a separate utility library
ko.bindingHandlers.fadeVisible = {
    init: function (element, valueAccessor) {
        // Initially set the element to be instantly visible/hidden depending on the value       
        var value = valueAccessor();
        // Use "unwrapObservable" so we can handle values that may or may not be observable    
        $(element).toggle(ko.utils.unwrapObservable(value));
    },
    update: function (element, valueAccessor) {
        // Whenever the value subsequently changes, slowly fade the element in or out        
        var value = valueAccessor();
        ko.utils.unwrapObservable(value) ? $(element).fadeIn() : $(element).fadeOut();
    }
};
ko.applyBindings(viewModel);

